from utils.mongo_util import db


def find_wechat_login(depart_id):
    # 第一步：查询部门信息获取userId列表
    depart_doc = db['sys_depart'].find_one(
        {'id': int(depart_id)},
        {'offMessageUsers.userId': 1, '_id': 0}
    )
    if not depart_doc or 'offMessageUsers' not in depart_doc:
        return []
    user_ids = [user['userId'] for user in depart_doc['offMessageUsers']]

    # 第二步：批量查询微信登录信息
    openid_query = db['sys_wechatlogin'].find(
        {'userId': {'$in': user_ids}, 'validState': {'$ne': 0}},
        {'gzhopenid': 1, '_id': 0}
    )

    # 转换为字符串数组并去重
    openids = list({
        str(item['gzhopenid'])
        for item in openid_query
        if 'gzhopenid' in item
    })

    return openids



